import React from 'react'
import ReactDOM from 'react-dom'
import * as MenuActions  from '../actions/MenuActions';
import { connect }  from 'react-redux';
import MenuSettingEditor from './MenuSettingEditor'
import MenuSettingPreview from './MenuSettingPreview'
import MenuSettingAssetSelect from './MenuSettingAssetSelect'
import MenuSettingTextEditor from './MenuSettingTextEditor'
import * as AssetByIdAction  from '../actions/AssetByIdAction';
import * as MessageAction from '../actions/MessageAction'

class MenuSettingBody extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      activeButtonIndex: null,
      activeSubIndex: null,
      isSubButton: false
    }

  }

  componentDidMount() {
    var self = this;
    this.$assetModal = $(ReactDOM.findDOMNode(this.refs.MenuSettingAssetSelect))
    this.$messageModal = $(ReactDOM.findDOMNode(this.refs.MenuSettingTextEditor))
    this.props.dispatch(
      MenuActions.loadMenusAsync()
    )
    // this.$assetModal.modal("show")
  }

  componentWillReceiveProps(props) {
    if (props.message) {
      this.setState({
        activeMessage: props.message
      })
    }
  }

  componentDidUpdate() {
    // console.log(this.props.buttons)
    // console.log(this.props.message)
    // console.log(this.props.buttons[0].type)
  }

  onMenuClick(buttonIndex, subIndex, isSubButton=false) {
    var buttons = this.props.buttons;
    if (buttonIndex != null && buttonIndex < buttons.length) {
      var button = buttons[buttonIndex];
      var subButtons = button.sub_button;
      if (subIndex != null && subIndex >= subButtons.length) {
        subIndex = null;
      }
    }else {
      buttonIndex = null;
      subIndex = null;
    }
    this.setState({
      activeButtonIndex: buttonIndex,
      activeSubIndex: subIndex,
      isSubButton: isSubButton
    })
  }

  onSelectMediaClick() {
    this.$assetModal.modal("show")
    // console.log(this.props.buttons[0].type)
  }

  onEditEventText(key) {
    if (key && key.length > 0) {
      this.props.dispatch(
        MessageAction.loadMessageHandlerOneAsync({
          msgType: 'event',
          event: 'click',
          eventKey: key
        })
      )
    }else {
      this.setState({
        activeMessage: null
      })
    }

    this.$messageModal.modal("show")
  }

  onMessageDataSubmit(data) {
    var button = this.getActiveButton();
    button.key = data.eventKey;
    button.type = 'click'
    if (this.state.activeMessage) {
      this.props.dispatch(
        MessageAction.updateMessageHandlerAsync(data)
      )
    }else {
      this.props.dispatch(
        MessageAction.createMessageHandlerAsync(data)
      )
    }
    this.$messageModal.modal("hide")
  }

  onMenuValueChange(buttons, activeIndex, activeSubIndex) {
    // console.log(this.props.buttons[0].type)
    this.setState({
      activeButtonIndex: activeIndex,
      activeSubIndex: activeSubIndex
    })

    this.props.dispatch(
      MenuActions.editMenu(buttons)
    )
  }

  onMenuSubmit(event) {

    var buttons = this.props.buttons;
    // console.log(buttons)
    for (var i = 0; i < buttons.length; i++) {
      var button = buttons[i];
      if (button.name.trim().length == 0) {
        alert("请输入菜单名称!")
        return;
      }
      for (var j = 0; j < button.sub_button.length; j++) {
        var sub = button.sub_button[j];
        if (sub.name.trim().length == 0) {
          alert("请输入菜单名称!")
          return;
        }
      }
    }
    this.props.dispatch(
      MenuActions.createMenuAsync({"button": buttons})
    )
  }

  onMenuReset() {
    if (confirm("确定要初始化菜单吗? 重置后, 将覆盖现有菜单内容")) {
      this.props.dispatch(
        MenuActions.resetMenuAsync()
      )
    }
  }

  onAssetGridClick(media_id, data) {
    this.$assetModal.modal("hide")
    var button = this.getActiveButton();
    button.type = 'media_id';
    button.media_id = media_id;
    this.onMenuValueChange(this.props.buttons, this.state.activeButtonIndex, this.state.activeSubIndex)
    this.props.dispatch(
      AssetByIdAction.loadAssetById(data, media_id)
    )
  }

  getActiveButton() {
    var activeButtonIndex = this.state.activeButtonIndex,
        activeSubIndex = this.state.activeSubIndex,
        buttons = this.props.buttons,
        button = null;
    if (this.state.isSubButton) {
      if (activeButtonIndex != null && buttons.length > activeButtonIndex) {
        var subButtons = buttons[activeButtonIndex].sub_button;
        if (activeSubIndex != null && subButtons.length > activeSubIndex) {
          button = subButtons[activeSubIndex];
        }
      }
    }else {
      if (activeButtonIndex != null && buttons.length > activeButtonIndex) {
        button = buttons[activeButtonIndex];
      }
    }

    return button;
  }

  render() {
    var self = this;
    return (
      <div className="content-body menu-setting-body" >
        <MenuSettingAssetSelect
          wechat = {this.props.wechat}
          onAssetGridClick = {this.onAssetGridClick.bind(self)}
          ref="MenuSettingAssetSelect"/>
        <MenuSettingPreview
          buttons = {this.props.buttons}
          activeButtonIndex = {this.state.activeButtonIndex}
          activeSubIndex = {this.state.activeSubIndex}
          isSubButton = {this.state.isSubButton}
          onMenuClick = {this.onMenuClick.bind(this)}/>
        <MenuSettingEditor
          wechat = {this.props.wechat}
          buttons = {this.props.buttons}
          activeSubIndex = {this.state.activeSubIndex}
          activeButtonIndex = {this.state.activeButtonIndex}
          isSubButton = {this.state.isSubButton}
          onMenuValueChange = {this.onMenuValueChange.bind(this)}
          onEditEventText = {this.onEditEventText.bind(self)}
          onSelectMediaClick = {this.onSelectMediaClick.bind(this)}/>
        <MenuSettingTextEditor
          ref="MenuSettingTextEditor"
          property = {this.props.property}
          onDataSubmit = {this.onMessageDataSubmit.bind(self)}
          data = {this.state.activeMessage}/>
        <div className="menu-submit">
          <button className="btn btn-success"
                  onClick={(event)=>this.onMenuSubmit(event)}>保存并发布</button>
          <button className="btn btn-danger"
                  onClick={(event)=>this.onMenuReset(event)}>初始化</button>
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return { buttons: state.menus,
           message: state.message.data
         }
}

export default connect(mapStateToProps)(MenuSettingBody)
